<?php 
	class ManageController extends CustomControllerAction {

		public function init() {
			parent::init();
			$this->_redirector = $this->_helper->getHelper('Redirector');
		}
		
		# indexAction: Controller for the main /manage page where they can make edits
		# to all of their submitted media
		public function indexAction() {
			
			$auth = Zend_Auth::getInstance();

			if ($auth->hasIdentity()) {
				
				$user_id = $auth->getIdentity()->id;

				# How many media pieces to get
				$limit = 10;

				# Get media this user has submitted
				$media_obj = new MediaSDBManager();
				$medias = $media_obj->query("['user_id' = '$user_id'] intersection ['date' > '0'] sort 'date' desc", $limit);
				
				foreach($medias as $media) {
					$photo_id = $media->getId();
					$users_stuff[$photo_id] = $media->getAttributes();
					$users_stuff[$photo_id]['id'] = $photo_id;

					# Get thumbnail
					$desired_thumb_width = "80";
					$thumb_mgr = new ThumbnailManager($this->_sdb, $this->_s3, $this->_config, $this->_logger);
					$users_stuff[$photo_id]['thumb_url'] = $thumb_mgr->getThumbnail($photo_id, $desired_thumb_width);
				}

				# Send the user's stuff to the view
				$this->view->media = $users_stuff;
			}
		}


		# deleteAction: Handles the deletion of media items
		public function deleteAction() {
			
			$del_id = $this->getRequest()->getPost('del_id');

			if ($del_id) {
				print $del_id;
				# Delete the media piece
				$media_obj = new Media();
				$media_obj->load($del_id);
				$response = $media_obj->delete($del_id);
				
				# Delete comments associated with this media piece?

				# Delete the media from the S3 server

				# Redirect to /manage/
				$this->_redirector = $this->_helper->getHelper('Redirector');
				$this->_redirector->gotoURL("/manage");
			}
		}
		

		# editAction: Handles editing information associated with media items
		public function editAction() {
			
			# Get logged in user's identity
			$auth = Zend_Auth::getInstance();

			if ($auth->hasIdentity()) {

				# Get the id of the photo to edit
				$photo_id = $this->getRequest()->getPost('id');

				if ($photo_id) {
					
					# Make sure the logged in user owns this photo
					$media = new Media();
					$media->load($photo_id);

					if ($media->getAttribute('user_id') == $auth->getIdentity()->id) {
						
						# Filter the new title
						$htmlEntities = new Zend_Filter_HtmlEntities();
						$filtered_title = $htmlEntities->filter($this->getRequest()->getPost('title'));

						# Reset the media url in the database
						$unique_url = CommonGenerator::generateUniqueMediaUrlString($filtered_title);


						# Edit media attributes
						$attributes = array('title' => $filtered_title, 'url' => $unique_url);

						try {
							$media->setAttributes($attributes);
							$media->save();
						}
						catch (Exception $e) {
							print $e; die();
						}
					}
				}
			}

			# Redirect back to manage home
			$this->_redirector->gotoURL('/manage');
		}
	}
